#include <stdio.h>
#include <string.h>
#include "mongoose.h"
#include "cJSON.h"
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))

void helloJSON_handle(struct mg_connection* c){
    cJSON* root, * sub1, * sub2, * sub3;

    root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "name", "张三");
    cJSON_AddNumberToObject(root, "age", 20);

    sub1 = cJSON_AddObjectToObject(root, "contact");
    cJSON_AddStringToObject(sub1, "email", "zhangsan@example.com");
    cJSON_AddStringToObject(sub1, "phone", "123456789");

    sub2 = cJSON_AddArrayToObject(root, "hobbies");
    cJSON_AddItemToArray(sub2, cJSON_CreateString("reading"));
    cJSON_AddItemToArray(sub2, cJSON_CreateString("sports"));

    sub3 = cJSON_AddBoolToObject(root, "is_student", cJSON_True);

    char* json_str = cJSON_Print(root);
    mg_printf(c, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %lu\r\n\r\n%s", strlen(json_str), json_str);
    free(json_str);
    cJSON_Delete(root);
}

void login_handle(struct mg_connection* c, struct mg_http_message* hm) {
    char username[20];
    char passworld[20];
    struct mg_str username_s = mg_http_var(hm->query, mg_str("username"));
    struct mg_str password_s = mg_http_var(hm->query, mg_str("password"));

    memset(username,0,sizeof(username));
    memset(passworld,0,sizeof(username));
    memcpy(username, username_s.ptr, min(username_s.len,sizeof(username)-1));
    memcpy(passworld, password_s.ptr, min(password_s.len,sizeof(passworld)-1));

    printf("测试登录接口，账号为:%s，密码为:%s\r\n", username, passworld);

    if (!strcmp("admin",username) && !strcmp("123456", passworld)) {
        printf("密码正确\n");
        mg_http_reply(c, 302, "Location: /success.html\r\n", "");
    }
    else {
        printf("密码错误\n");
        mg_http_reply(c, 302, "Location: /fail.html\r\n", "");
    }
}


static void fn(struct mg_connection* c, int ev, void* ev_data, void* fn_data) {
    if (ev == MG_EV_HTTP_MSG) {
        struct mg_http_message* hm = (struct mg_http_message*)ev_data;
        if (mg_http_match_uri(hm, "/")) {
            //根目录重定向
            mg_http_reply(c, 302, "Location: /login.html\r\n", "");
        } else if (mg_http_match_uri(hm, "/api/hello")) {
            //测试API
            helloJSON_handle(c);
        }else if (mg_http_match_uri(hm, "/login")) {
            //登录API
            login_handle(c, hm);
        }else{
            //文件服务
            struct mg_http_serve_opts opts = { .root_dir = "./www" };
            mg_http_serve_dir(c, hm, &opts);
        }
    }
}

int main(void) {
    struct mg_mgr mgr;
    mg_mgr_init(&mgr);                                      // Init manager
    mg_http_listen(&mgr, "http://0.0.0.0:8000", fn, &mgr);  // Setup listener
    for (;;) mg_mgr_poll(&mgr, 1000);                       // Infinite event loop
    return 0;
}
